package com.wtf.dsp.admin.core.executor;


import com.baomidou.mybatisplus.annotation.DbType;
import com.wtf.dsp.admin.core.config.WtfDspAdminConfig;
import com.wtf.dsp.admin.core.dao.AbstractJdbcDao;
import com.wtf.dsp.admin.core.model.DataSourceInfo;
import com.wtf.dsp.admin.core.provider.AbstractWtfDynamicDataSourceProvider;
import com.wtf.dsp.admin.core.provider.DynamicDataSourceConfigProvide;
import com.wtf.dsp.admin.entity.WtfDspDatasource;
import com.wtf.dsp.admin.enums.CommonErrorEnum;
import com.wtf.dsp.admin.exception.WtfDspException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;


/**
 * date: 2022/6/18 10:59
 * @author linhuanyou
 * @email 496558736@qq.com
 * @version 1.0
 */
@Slf4j
public class WtfDynamicDataSourceProviderExecutor extends AbstractWtfDynamicDataSourceProvider {
    private WtfDspAdminConfig dspAdminConfig;
    public WtfDynamicDataSourceProviderExecutor(WtfDspAdminConfig wtfDspMapperConfig , DynamicDataSourceConfigProvide dynamicDataSourceConfigProvide, AbstractJdbcDao databaseDao) {
        super(dynamicDataSourceConfigProvide,databaseDao);
        this.dspAdminConfig = wtfDspMapperConfig;
    }

    @Override
    public List<DataSourceInfo> getDataSources() {
        return dspAdminConfig.getWtfDspDatasourceMapper().loadDataSource().stream().map(e->{
            DataSourceInfo dataSourceInfo = new DataSourceInfo();
            BeanUtils.copyProperties(e,dataSourceInfo);
            dataSourceInfo.setDbType(DbType.getDbType(e.getDbType()));
            return dataSourceInfo;
        }).collect(Collectors.toList());
    }

    @Override
    public DataSourceInfo getDataSource(String ns, String ds) {
        WtfDspDatasource dspDatasource = dspAdminConfig.getWtfDspDatasourceMapper().getDataSource(ns,ds);
        if(dspDatasource == null){
            throw new WtfDspException(CommonErrorEnum.DATA_SOURCE_NOT_EXIST);
        }
        DataSourceInfo dataSourceInfo = new DataSourceInfo();
        BeanUtils.copyProperties(dspDatasource,dataSourceInfo);
        dataSourceInfo.setDbType(DbType.getDbType(dspDatasource.getDbType()));
        return dataSourceInfo;
    }
}
